package com.gzx.risk.app.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.AccessDeniedHandler;

@Configuration
@EnableWebSecurity
public class SwaggerSecurityConfig {

	// 1. 定义安全过滤链规则
	@Bean
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
				// 配置URL授权规则
				.authorizeHttpRequests(
						authorize -> authorize.requestMatchers("/api/risk/riskOrder", "/api/risk/hello",
                                        "/api/order/ext/queryContractAndUserExt").permitAll() // 公开访问
                                .requestMatchers("/feign/**").permitAll()
								.requestMatchers("/api/**", "/apis/**").access((authentication, context) -> {
									String headerValue = context.getRequest().getHeader("X-Self");
									boolean hasValidHeader = "gzx".equals(headerValue);
									return new AuthorizationDecision(hasValidHeader);
								})
								.requestMatchers("/favicon.ico", "/do-login", "/login", "/login.html", "/css/**",
										"/js/**", "/api/risk/riskOrder")
								.permitAll() // 公开访问
								.requestMatchers("/", "/swagger-ui/**", "/v3/api-docs/**").hasRole("ADMIN")
								.requestMatchers("/api/**", "/apis/**").hasRole("ADMIN")
                )

				// 配置表单登录
				.formLogin(form -> form.loginPage("/login.html") // 自定义登录页路径
						.loginProcessingUrl("/do-login").defaultSuccessUrl("/api/info/list", true) // 登录成功默认跳转页
						.failureUrl("/login.html?error=true") // 登录失败跳转页
						.permitAll() // 允许所有人访问登录相关页面
				)
				// 配置退出登录
				.logout(logout -> logout.logoutUrl("/logout") // 退出登录URL
						.logoutSuccessUrl("/login.html?logout=true") // 退出成功跳转页
						.invalidateHttpSession(true) // 使会话失效
						.permitAll())
				// rememberMe
				.rememberMe(remember -> remember.tokenValiditySeconds(60 * 60 * 24 * 7) // 记住我有效期（7天）
						.rememberMeParameter("remember-me") // 前端参数名
				) // 配置403处理：使用自定义处理器重定向到登录页
				.exceptionHandling(ex -> ex.accessDeniedHandler(accessDeniedHandler()))
				// 禁用
				.csrf(csrf -> csrf.disable());

		return http.build();
	}

	@Bean
	public PasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Bean
	public AccessDeniedHandler accessDeniedHandler() {
		return new CustomAccessDeniedHandler();
	}
}